package mac5855.app.controllers;

import java.util.Date;

import mac5855.app.dao.DAOFactory;
import mac5855.app.dao.UsuarioDAO;
import mac5855.app.models.Usuario;

public class UserBean {
	
	private String username = "";
	private String password = "";
	private long lastlogon;
	
	public void setUsername(String username) {
		this.username = username;
	}

	public String getUsername() {
		return username;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getPassword() {
		return password;
	}
	
	public Long getLastlogon() {
		lastlogon = System.currentTimeMillis();
		return lastlogon;
	}

	public void setLastlogon(Long lasLong) {
		lastlogon = lasLong;
	}
	
	public String login() {
		if ((username != null && password != null) && (username.length() > 0)) {
			Usuario usuario = validUser(username, password);
			if (usuario != null) {
				if (lastlogon > usuario.getUltimoLogin().getTime()) {
					usuario.setUltimoLogin(new Date(lastlogon));
					UsuarioDAO usuarioDAO = DAOFactory.getDAOFactory(DAOFactory.JDBC).getUsuarioDAO();
					usuarioDAO.updateLastLogon(usuario);
					// session.setAttribute(USER_KEY, usuario.getEmail());
					// session.setAttribute(USER_TYPE, usuario.getTipo());
					return "success";
				}
			}
		}
		return "fail";
	}

	protected Usuario validUser(String username, String password) {

		UsuarioDAO usuarioDAO = DAOFactory.getDAOFactory(DAOFactory.JDBC).getUsuarioDAO();

		if ((username != null) && (username.length() > 0)) {
			Usuario userFind = new Usuario();
			userFind.setEmail(username);
			userFind.setSenha(password);
			Usuario usuario = usuarioDAO.find(userFind);
			if (usuario != null) {
				return usuario;
			}

		}

		return null;
	}

}
